import { Controller, Post, Body, Logger } from '@nestjs/common';
import type { ProxyDto } from './dto/proxy.dto';

@Controller('proxy')
export class ProxyController {
  logger = new Logger(ProxyController.name);
  /**
   * post 接口代理
   */
  @Post('handle') async handle(@Body() body: ProxyDto) {
    this.logger.log(`handle proxy request: ${body.url}`, body.method);
    const res = await fetch(body.url, {
      method: body.method || 'GET',
      headers: body.headers,
      body: body.body,
    });
    if (
      res.headers.has('content-type') &&
      res.headers.get('content-type')?.includes('application/json')
    ) {
      const data = (await res.json()) as unknown;
      this.logger.log(`handle proxy response: ${body.url}`, data);
      return { data, $isTop: true };
    }
    return { data: await res.text(), $isTop: true };
  }
}
